import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, NgControl, Validators } from '@angular/forms';
import { NzFormTooltipIcon } from 'ng-zorro-antd/form';
import { Student } from '../inerface/datatype.service';
import { Grade } from '../inerface/datatype.service';
import { ColumnItem } from '../inerface/datatype.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import * as echarts from 'echarts'
@Component({
  selector: 'app-table-demo',
  templateUrl: './table-to-form.component.html',
  styleUrls: ['./table-to-form.component.scss']
})
export class TableToFormComponent implements OnInit {



  // 实例化-班级对象--表格数据
  listOfData: Grade[] = [
    {
      grade: '计科1901',
      student: [
        {
          name: "小明",
          id: '201931878',
          gender: '男',
          email: '30342342@qq.com',
          mobile: '13578655678'
        },
        {
          name: "小青",
          id: '201931874',
          gender: '女',
          email: '7893124@qq.com',
          mobile: '13578655678'
        }
      ]
    },
    {
      grade: '计科1902',
      student: [
        {
          name: "小刚",
          id: '201931871',
          gender: '男',
          email: '30342344@qq.com',
          mobile: '13578655678'
        },
        {
          name: "小佳",
          id: '201931875',
          gender: '女',
          email: '32427676@qq.com',
          mobile: '13578655678'
        }]
    },
    {
      grade: '计科1903',
      student: [
        {
          name: "小强",
          id: '201931872',
          gender: '男',
          email: '3034542342@qq.com',
          mobile: '13578655678'
        },
        {
          name: "小清",
          id: '201931876',
          gender: '女',
          email: '94672@qq.com',
          mobile: '13578655678'
        }]
    },
    {
      grade: '计科1904',
      student: [
        {
          name: "小芳",
          id: '201931873',
          gender: '女',
          email: '456442@qq.com',
          mobile: '13578655678'
        },
        {
          name: "小花",
          id: '201931877',
          gender: '女',
          email: '2345667@qq.com',
          mobile: '13578655678'
        }]
    },
  ];
  // 每一行数据的来源
  listOfColumns: ColumnItem[] = [
    {
      name: '姓名',
      id: '学号',
      grade: '班级',
      gender: '性别',
      email: '邮箱',
      mobile: '电话',
      filterFn: (list: string[], item: Grade) => list.some(name => item.grade.indexOf(name) !== -1),
      // nameFilterFn = (list: string[], item: DataItem): boolean => list.some(name => item.name.indexOf(name) !== -1);
      // 班级筛选
      listOfFilter: [],
    },
  ];


  public isEdit = false;
  // 班级、学号ID数组
  public gradeList: String[] = [];
  //空的IdList,用于判断是否重复
  public IdList: string[] = []
  // 页标签，跳转界面的标志
  public flag: number = 1;
  //删除操作之后的listOfData
  public listDataAftterDel: Student[] = [];


  //界面切换
  showModal(): void {
    this.isVisible = true;
    this.flag = 2;
  }
  showModal2(): void {
    this.isVisible = true;
    this.flag = 3;
  }


  // 得到原始数据的gradeList,利用set去重
  getgrade() {
    for (let i = 0; i < this.listOfData.length; i++) {
      // console.log(this.listOfData[i].grade);
      this.gradeList.push(this.listOfData[i].grade)
      this.gradeList = [...new Set(this.gradeList)]
    }
    return this.gradeList
  }

  //得到学号List
  getID() {
    for (let i = 0; i < this.listOfData.length; i++) {
      for (let j = 0; j < this.listOfData[i].student.length; j++) {
        let tmp = this.listOfData[i].student[j]
        this.IdList.push(tmp.id);
      }
    }
    return this.IdList;
  }

  // validateForm 数据声明
  validateForm!: FormGroup;
  validateForm2!: FormGroup;
  captchaTooltipIcon: NzFormTooltipIcon = {
    type: 'info-circle',
    theme: 'twotone'
  };

  // 新建班级数据提交
  submitForm(): void {
    //判断是否存在，存在报错并不进行后续操作
    for (let i = 0; i < this.gradeList.length; i++) {
      let erro = 0;
      if (this.validateForm.value.grade == this.gradeList[i]) {
        erro = 1;
      }
      if (erro == 1) {
        //弹出错误，数据不提交
        alert("输入的班级已经存在")
        return
      }
    }
    //数据的提交
    let tmp_grade: Grade = {
      grade: this.validateForm.value.grade,
      student: []
    };
    this.gradeList.push(this.validateForm.value.grade);
    //同步更新，班级筛选中的可选班级
    this.listOfColumns[0].listOfFilter.push({ text: String(this.validateForm.value.grade), value: this.validateForm.value.grade })
    this.listOfData.push(tmp_grade);
    console.log(this.listOfData)
  }

  // 新建学生数据提交
  submitForm2(): void {
    console.log(this.IdList)
    //添加的学生信息ID已经存在
    console.log(this.isEdit)
    //初始为false，不执行
    if (this.isEdit) {
      for (let i = 0; i < this.IdList.length; i++) {
        let erro = 0;
        if (this.validateForm2.value.id == this.IdList[i]) {
          erro = 1;
          if (erro == 1) {
            alert("输入的学号已经存在");
            return;
          }
        }
      }
    }
    //提交学生信息
    console.log('新增加即将提交的student信息', this.validateForm2.value);
    let tmp_stu: Student = {
      name:this.validateForm2.value.name,
      id:this.validateForm2.value.id,
      gender:this.validateForm2.value.gender,
      email:this.validateForm2.value.email,
      mobile:this.validateForm2.value.mobile
    };
    this.listOfData.forEach(item =>{
      if(item.grade === this.validateForm2.value.grade){
        item.student.push(tmp_stu)
      }
    })
    console.log('提交数据之后的ListOfData:', this.listOfData);
  }
  // 存放新增加的学生信息
  tmp_student: Student[] = [];



  // // 根据name进行搜索
  // trackByName(_: number, item: ColumnItem): string {
  //   return item.name;
  // }

  //返回按钮
  backTable() {
    this.isVisible = false;
    this.flag = 1;
  }
  // 添加学生信息
  isVisible = false;
  constructor(private fb: FormBuilder,
    private message: NzMessageService) {
  }

  // 更新班级信息
  handleOk(): void {
    console.log('Button ok clicked!');
    //提交信息
    console.log(this.submitForm());
    this.isVisible = false;
    this.flag = 1
    console.log('this.getGrade', this.getgrade())
    // this.selectGrade();
  }


  // 弹出框确认按钮、添加学生信息
  handleOk2(): void {
    console.log('Button ok clicked!');
    if(!this.isEdit){
      console.log(this.submitForm2());
    }
    this.isVisible = false;
    this.flag = 1
  }


  //最返回
  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
  }


  //变更学生元素
  editInfo(grade: string, student: Student) {
    //变更
    //界面显示
    this.isEdit = true;
    this.isVisible = true;
    this.flag = 3;
    //  已经有的信息的展示
    this.validateForm2 = this.fb.group({
      grade: [grade, [Validators.required]],
      id: [student.id, [Validators.required]],
      name: [student.name, [Validators.required]],
      gender: [student.gender, [Validators.required]],
      email: [student.email, [Validators.email, Validators.required]],
      mobile: [student.mobile, [Validators.required]],
    })

    //  未改变student信息，就去到grade里面删除原来的student，添加进来提交的student
    let afterEditStudent:Student = {
      id : this.validateForm2.value.id,
      name : this.validateForm2.value.name,
      gender : this.validateForm2.value.gender,
      email : this.validateForm2.value.email,
      mobile : this.validateForm2.value.mobile
    }
    console.log(afterEditStudent)
     if(grade === this.validateForm2.value.grade){
       console.log("没有改变班级")
       this.listOfData.forEach(item => {
          if(item.grade === this.validateForm2.value.grade){
            item.student.forEach((thisStudent,index)=>{
              if(thisStudent.id === this.validateForm2.value.id){
                item.student.splice(index,1)
                // thisStudent.id = this.validateForm2.value.id
                //   thisStudent.name = this.validateForm2.value.name
                //   thisStudent.gender = this.validateForm2.value.gender
                //   thisStudent.email = this.validateForm2.value.email
                //   thisStudent.mobile = this.validateForm2.value.mobile
                console.log(3)
                // item.student.push(afterEditStudent)
                // thisStudent = afterEditStudent
              }
            })
          }
       })
     }else {
       console.log("改变了班级")
       this.listOfData.forEach(item => {
         if(item.grade === grade){
           item.student.forEach((thisStudent,index)=>{
            if(thisStudent.id === student.id){
              item.student.splice(index,1)
            }
           })
         }
         if(item.grade === this.validateForm2.value.grade){
           item.student.push(afterEditStudent)
         }

       })

     }


    // if (this.validateForm2.value.grade == grade) {
    //   for (let i = 0; i < this.listOfData.length; i++) {
    //     for (let j = 0; j < this.listOfData[i].student.length; j++) {
    //       if (this.listOfData[i].student[j].id == student.id) {
    //         this.validateForm2.value.id = student.id;
    //         this.validateForm2.value.gender = student.gender;
    //         this.validateForm2.value.email = student.email;
    //         this.validateForm2.value.mobile = student.mobile;
    //       }
    //     }
    //   }
    // }

    //  如果修改了grade的话，就需要删除原来的信息，重新写入一条信息
    // if (this.validateForm2.value.grade != grade) {
    //   console.log('触发了更改学生信息')
    //   //删除学生信息
    //   this.delInfo(grade, student);
    //   //  添加一条新的信息
    //   this.submitForm2()
    // }
    console.log("删除之后的gradeList:", this.getgrade())
    console.log(grade, student)
    this.isEdit = false;
  }


  //删除行元素
  delInfo(grade: string, student: Student) {
    //删除保存的student数据
    // let gradeArr = this.listOfData.filter(item=> item.grade === grade)
    // let theStudentArr = gradeArr[0].student.filter(item => item.id === student.id)
    // let theStudent = theStudentArr[0]
    this.listOfData.forEach(item =>{
      if(item.grade === grade)
      {
        item.student.forEach((studentItem,index)=>{
          if(studentItem.id === student.id){
            item.student.splice(index,1);
          }
          }
        )
      }
    })
    //
    // for (let i = 0; i < this.listOfData.length; i++) {
    //   for (let j = 0; j < this.listOfData[i].student.length; j++) {
    //     if (this.listOfData[i].student[j].id == student.id) {
    //       this.listOfData[i].student.splice(j);
    //     }
    //   }
    //   for (let k = 0; k < this.listOfData[i].student.length; k++) {
    //     this.listDataAftterDel.push(this.listOfData[i].student[k]);
    //   }
    // }
    console.log("删除过后的ListOfData:", this.listOfData)
    console.log("删除操作之后的gradeList", this.getgrade())
  }

  // selectGrade(){
  //   console.log("slelect中传进来的gradelist",this.gradeList)
  //   for(let i =0;i<this.gradeList.length;i++) {
  //     this.listOfColumns[0].listOfFilter.push({text: String(this.gradeList[i]), value: this.gradeList[i]})
  //   }
  //   for(let j = 0;j<this.listOfColumns[0].listOfFilter.length;j++){
  //     for(let k= j+1;k<this.listOfColumns[0].listOfFilter.length;k++){
  //       if(this.listOfColumns[0].listOfFilter[j].text == this.listOfColumns[0].listOfFilter[k].text){
  //         this.listOfColumns[0].listOfFilter.splice(k)
  //       }
  //     }
  //   }
  //   console.log("双重for去重",this.listOfColumns[0].listOfFilter)
  // }


  ngOnInit(): void {
    console.log("现在的学生班级：", this.getgrade())
    console.log("现在的学生信息：", this.listOfData)
    console.log("现在的学生ID：", this.getID())
    for (let i = 0; i < this.gradeList.length; i++) {
      this.listOfColumns[0].listOfFilter.push({ text: String(this.gradeList[i]), value: this.gradeList[i] })
    }
    this.validateForm = this.fb.group({
      grade: [null, [Validators.required]],
      name: [null, [Validators.required]],
      gender: [null, [Validators.required]],
      email: [null, [Validators.email, Validators.required]],
      mobile: [null, [Validators.required]],
    });

    this.validateForm2 = this.fb.group({
      grade: [null, [Validators.required]],
      id: [null, [Validators.required]],
      name: [null, [Validators.required]],
      gender: ['男', [Validators.required]],
      email: [null, [Validators.email, Validators.required]],
      mobile: [null, [Validators.required]],
    });
  }

}
